package com.proxy.parser.tree.sql;

import com.proxy.parser.tree.sql.ast.SQLExpr;
import com.proxy.parser.tree.sql.ast.SQLLimit;
import com.proxy.parser.tree.sql.ast.expr.SQLIdentifierExpr;
import com.proxy.parser.tree.sql.ast.expr.SQLIntegerExpr;
import com.proxy.parser.tree.sql.ast.expr.SQLPropertyExpr;
import com.proxy.parser.tree.sql.ast.statement.SQLExprTableSource;
import com.proxy.parser.tree.sql.ast.statement.SQLTableSource;
import com.proxy.parser.tree.sql.dialect.mysql.ast.statement.MySqlSelectQueryBlock;

/**
 * 改变原有的sql
 *
 * Created by liufish on 17/2/19.
 */
public class SQLParserUtils {


    /**
     * 改变原有的db
     *
     * 把 'pay.user'  变成  user
     * @param selectQueryBlock
     */
    public static void removeSchema(MySqlSelectQueryBlock selectQueryBlock){

        SQLTableSource tableSource = selectQueryBlock.getFrom();

        if(tableSource == null){
            return;
        }

        if(tableSource instanceof SQLExprTableSource){
            SQLExprTableSource sqlExprTableSource = (SQLExprTableSource)tableSource;
            SQLExpr sqlExpr =  sqlExprTableSource.getExpr();

            //去掉一级查询 select * from cat.user 里面的cat.
            if(sqlExpr instanceof SQLPropertyExpr){
                SQLIdentifierExpr sqlIdentifierExpr = new SQLIdentifierExpr();
                sqlIdentifierExpr.setName(((SQLPropertyExpr) sqlExpr).getName());
                sqlExprTableSource.setExpr(sqlIdentifierExpr);
            }
        }

    }


    /**
     * 当路由到没有分片的sql语句,或者分片到多个数据库的sql语句,就要更改limit属性
     *
     * limit 10,100 改写成 limit 0,110
     *
     *  @param selectQueryBlock
     */
    public static void changeLimit(MySqlSelectQueryBlock selectQueryBlock){

        SQLLimit limit =  selectQueryBlock.getLimit();

        SQLIntegerExpr offsetExpr = (SQLIntegerExpr) limit.getOffset();

        SQLIntegerExpr rowCountExpr = (SQLIntegerExpr) limit.getRowCount();

        if(offsetExpr != null){
            limit.setRowCount(new SQLIntegerExpr( offsetExpr.getNumber().longValue() + rowCountExpr.getNumber().longValue()));
        }
        limit.setOffset(new SQLIntegerExpr(0));

    }


}
